<template>
  <div>
    <Row>
      <Col span="24">
        <Button @click="update">保存</Button>
      </Col>
    </Row>
    <Row>
      <Col span="24" style='margin-top:15px;margin-right:10px'>
        <Tree :data="treeData" ref="menuTree" show-checkbox ></Tree>
      </Col>
    </Row>
  </div>
</template>
<script>
import {
  modifyMenuAuthority,
  getMenuAuthority
} from '@/api/sys/role'
import {
  fetchTree
} from '@/api/sys/menu'
import {
  convertTree,
  getLastIds
} from '@/libs/util'
export default {
  components: {
  },
  name: 'roleAuthority',
  props: {
    roleId: {
      default: '1'
    }
  },
  data () {
    return {
      role_id: '-1',
      treeData: [],
      treeMap: {}
    }
  },
  watch: {
    roleId (val) {
      this.role_id = val
    }
  },
  methods: {
    getList () {
      fetchTree().then(data => {
        const map = {
          value: 'id',
          label: 'label',
          children: 'children',
          childExpand: true
        }
        this.treeMap = {}
        this.treeData = convertTree(data, map, this.treeMap)
        this.initAuthoritys()
      })
    },
    update () {
      this.$emit('closeAuthorityDialog')
      const nodes = this.$refs.menuTree.getCheckedNodes()
      const ids = []
      for (let i = 0; i < nodes.length; i++) {
        ids.push(nodes[i].id)
      }
      modifyMenuAuthority(this.role_id, {
        menuTrees: ids.join()
      }).then(() => {
        this.$Notice.success({
          title: '成功',
          desc: '菜单权限保存成功'
        })
      })
    },
    initAuthoritys () {
      getMenuAuthority(this.role_id).then(data => {
        let ids = []
        for (let i = 0; i < data.data.length; i++) {
          getLastIds(ids, data.data[i])
        }
        ids.forEach(id => {
          if (this.treeMap[id]) {
            this.$set(this.treeMap[id], 'checked', true)
          }
        })
      })
    }
  }
}
</script>
